import { Menu, Checkbox, Button, Spin, message } from 'antd';
import classnames from 'classnames';

const MenuItem = Menu.Item;
const SubMenu = Menu.SubMenu;
import {
  WeaTools,
  WeaNewScrollPagination,
  WeaAlertPage,
  WeaDropdown,
  WeaTab,
  WeaFormItem,
  WeaSearchGroup,
  WeaLocaleProvider,
  WeaSelect,
} from 'ecCom';
import { WeaSwitch } from 'comsMobx';
import Item from './item';
import { inject, observer } from 'mobx-react';
import { createMarkMenu, createSortMenu } from '../../../util/CoworkUtil';
import CoworkConstant from '../../../util/CoworkConstant';

const getLabel = WeaLocaleProvider.getLabel;

@inject('coworkMainStore')
@observer
class CoworkList extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      labelKey: '',
      show: 'none',
      isJoin: false, // 直接参与的工作
      borderWhite: false,
      othersConcern: [],
      loading: true,
      searchValue: '',
      tabKey: 'all',
    };
  }

  onTran = (show) => {
    this.setState({
      show: show ? 'block' : 'none',
      borderWhite: show,
    });
  };

  onScrollEnd = () => {
    const { coworkMainStore } = this.props;
    let { setParams, getLeftList, leftList } = coworkMainStore;
    if (!coworkMainStore.leftList.ended) {
      // 加一层判断，已经到底了就不继续获取了
      setParams({ pageNum: leftList.params.pageNum + 1 });
      getLeftList();
    }
  };

  isConcern = (datas, isConcern, isJoin) => {
    datas &&
      datas.map((item) => {
        if (item.joinType === '0') {
          isConcern.push(item);
        } else {
          isJoin.push(item);
        }
      });
  };

  onEnterSearch = () => {
    this.search();
    this.props.coworkMainStore.setSearchAd(false);
  };

  onFormChange = (res, obj) => {
    const {
      coworkMainStore: { setStoreState },
    } = this.props;
    if (res && Object.keys(res)[0] === 'jointype') {
      setStoreState({ formJoinType: obj.value });
    }
  };

  getSearchs = (tabKey) => {
    let { form, condition } = this.props.coworkMainStore.leftList;
    const { isFormInit } = form;
    let group = [];
    const formParams = form.getFormParams();
    isFormInit &&
      condition &&
      condition.map((c) => {
        let items = [];
        c.items.map((fields) => {
          if (fields.domkey[0] == 'ishide' && tabKey === 'hidden') {
            return;
          }
          items.push({
            com: (
              <WeaFormItem
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaFormItem@0z7fhy@${fields.domkey[0]}`}
                label={`${fields.label}`}
                labelCol={{ span: 6 }}
                viewAttr={fields.viewAttr}
                wrapperCol={{ span: 18 }}
              >
                <WeaSwitch
                  ecId={`${
                    (this && this.props && this.props.ecId) || ''
                  }_WeaSwitch@i68w3w@${fields.domkey[0]}`}
                  fieldConfig={fields}
                  form={form}
                  formParams={formParams}
                  onEnterSearch={this.onEnterSearch}
                  onChange={this.onFormChange}
                />
              </WeaFormItem>
            ),
            colSpan: 1,
          });
        });
        group.push(
          <WeaSearchGroup
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaSearchGroup@jrrptt@searchgroup`}
            col={1}
            needTigger={false}
            showGroup={c.defaultshow}
            items={items}
          />,
        );
      });
    return group;
  };

  onTabSearch = () => {
    this.search();
    this.props.coworkMainStore.setSearchAd(false);
  };
  onTabCancel = () => {
    this.props.coworkMainStore.setSearchAd(false);
  };

  setShowSearchAd = () => {
    const {
      coworkMainStore: { leftList },
    } = this.props;
    let { showSearchAd } = leftList;
    this.props.coworkMainStore.setSearchAd(!showSearchAd);
  };

  hideSearchAd = () => this.props.coworkMainStore.setSearchAd(false);
  onTabChange = (key) => {
    key !== 'others' ? this.changeTabKey(key) : this.changeListKey(key);
  };

  onTabSearchChange = (value) => {
    const {
      coworkMainStore: { leftList },
    } = this.props;
    leftList.form.updateFields({ name: value });
  };

  render() {
    const {
      coworkMainStore: {
        leftList,
        config,
        contentId,
        formJoinType,
        checkLeftListAll,
      },
    } = this.props;
    let {
      form,
      datas,
      loading,
      ended,
      checkAll,
      params,
      alertPage,
      showSearchAd,
    } = leftList;
    let id = contentId;
    // leftList列表数据
    let isConcern = [];
    let isJoin = [];
    this.isConcern(datas, isConcern, isJoin);

    // tabs数据
    const labelList = config.labelList;
    const usedLabelList = labelList.filter(label => label.isUsed == 1) || [];
    let tabItems = [
      <MenuItem
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_MenuItem@yzpb2y@all`}
        key="all"
      >
        {getLabel(332, '全部')}
      </MenuItem>,
      <MenuItem
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_MenuItem@8n8zhp@unread`}
        key="unread"
      >
        {getLabel(25426, '未读')}
      </MenuItem>,
      <MenuItem
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_MenuItem@022bkj@important`}
        key="important"
      >
        {getLabel(382626, '标星')}
      </MenuItem>,
      <MenuItem
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_MenuItem@tgek0d@hidden`}
        key="hidden"
      >
        {getLabel(16636, '隐藏')}
      </MenuItem>,
    ];
    if (usedLabelList.length > 0) {
      tabItems.push(
        <SubMenu
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_SubMenu@pyx56x@subMenu`}
          title={
            <div className="list-tag-drop">
              {getLabel(382629, '按标签')} <span className="icon-coms-down" />
            </div>
          }
        >
          {usedLabelList.map(label => (
            <Menu.Item
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_MenuItem@05wwmy@${label.id}`}
              key={label.id}
            >
              {label.labelName}
            </Menu.Item>
          ))}
        </SubMenu>,
      );
    }

    const tabMenus = [
      {
        viewcondition: 'all',
        title: getLabel(332, '全部'),
      },
      {
        viewcondition: 'unread',
        title: getLabel(25426, '未读'),
      },
      {
        viewcondition: 'important',
        title: getLabel(382626, '标星'),
      },
      {
        viewcondition: 'hidden',
        title: getLabel(16636, '隐藏'),
      },
    ];
    let subMenus = [];
    if (usedLabelList.length > 0) {
      usedLabelList.map((item) => {
        let tempObj = {
          requestid: item.id,
          requestname: item.labelName,
        };
        subMenus.push(tempObj);
      });
      tabMenus.push({
        viewcondition: 'others',
        titleText: getLabel(382629, '按标签'),
        title: (
          <div className="list-tag-drop">
            {getLabel(382629, '按标签')} <span className="icon-coms-down" />
          </div>
        ),
        dropMenu: subMenus,
      });
    }

    let selectedKeys = params.type;
    if (
      ['all', 'unread', 'important', 'hidden'].every(
        key => key != selectedKeys,
      )
    ) {
      // selectedKeys = params.labelid;
      selectedKeys = 'others';
    }

    let userLanguage = window.e9_locale && window.e9_locale.userLanguage === 8;
    let listCls = classnames({
      'wea-cowork-list': true,
      bigFont:
        userLanguage ||
        (WeaTools.ls.getJSONObj('theme-themeInfo') &&
          WeaTools.ls.getJSONObj('theme-themeInfo').themeFontSize != '12' &&
          usedLabelList.length > 0),
    });

    const buttonsAd = [
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@0ebaxj@search`}
        type="primary"
        onClick={this.onTabSearch}
      >
        {getLabel(197, '搜索')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@q2y38a@reset`}
        type="ghost"
        onClick={this.props.coworkMainStore.doFormReset}
      >
        {getLabel(2022, '重置')}
      </Button>,
      <Button
        ecId={`${
          (this && this.props && this.props.ecId) || ''
        }_Button@4hognv@cancel`}
        type="ghost"
        onClick={this.onTabCancel}
      >
        {getLabel(201, '取消')}
      </Button>,
    ];

    return (
      <div className={listCls}>
        <div className="wea-cowork-list-tabs">
          <WeaTab
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTab@s4byut`}
            datas={tabMenus}
            keyParam="viewcondition"
            countParam="groupid"
            selectedKey={selectedKeys}
            onChange={this.onTabChange}
            subMenuClass="list-tag-droplist"
            hasDropMenu
          />
        </div>
        <div className="wea-cowork-list-adSearch">
          <WeaTab
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_WeaTab@vfnofx`}
            searchType={['base', 'advanced']}
            searchsAd={this.getSearchs(this.state.tabKey)}
            showSearchAd={showSearchAd}
            buttonsAd={buttonsAd}
            setShowSearchAd={this.setShowSearchAd}
            hideSearchAd={this.hideSearchAd}
            searchsBaseValue={
              (form.isFormInit &&
                form.getFormParams &&
                form.getFormParams().name) ||
              ''
            }
            onSearch={this.search}
            onSearchChange={this.onTabSearchChange}
          />
        </div>
        <div className="cowork-list-type">
          <Checkbox
            ecId={`${
              (this && this.props && this.props.ecId) || ''
            }_Checkbox@n0fh9x`}
            className="list-type-check"
            checked={checkAll}
            onChange={checkLeftListAll}
          />
          <div className="list-type-btns">
            {createSortMenu(params.orderType, this.changeSortKey)}
            <WeaDropdown
              ecId={`${
                (this && this.props && this.props.ecId) || ''
              }_WeaDropdown@b004jz`}
              overlay={createMarkMenu(labelList, this.mark)}
            >
              {getLabel(81293, '标记为')}...{' '}
            </WeaDropdown>
          </div>
        </div>
        <WeaSelect
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaSelect@e5woi2`}
          className="cowork-theme-drop"
          options={CoworkConstant.joinTypeMenu()}
          onChange={this.changeThemeKey}
          value={formJoinType}
          bordered={false}
          dropdownClassName={'cowork-theme-dropdown'}
        />
        <WeaNewScrollPagination
          ecId={`${
            (this && this.props && this.props.ecId) || ''
          }_WeaNewScrollPagination@4kue71`}
          onScrollEnd={this.onScrollEnd}
        >
          {!alertPage ? (
            <div>
              <div>
                <div className="wea-cowork-items">
                  <ul>
                    {datas.map(data => (
                      <Item
                        ecId={`${
                          (this && this.props && this.props.ecId) || ''
                        }_Item@70odum@${data.coworkid}`}
                        {...data}
                        choose={data.coworkid == id}
                      />
                    ))}
                  </ul>
                </div>
              </div>
            </div>
          ) : (
            <div className="cowork-leftlist-alert-page">
              <WeaAlertPage
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_WeaAlertPage@pqhe51`}
                top="25%"
                icon="icon-coms-blank"
              >
                <div>{getLabel(83553, '暂无数据')}</div>
              </WeaAlertPage>
            </div>
          )}

          {loading && !ended && (
            // <div style={{position: 'relative', height: '100%', textAlign: 'center', top: '45%'}}>
            <div style={{ position: 'relative', textAlign: 'center' }}>
              <Spin
                ecId={`${
                  (this && this.props && this.props.ecId) || ''
                }_Spin@anu00j`}
                spinning={this.state.loading}
              />
            </div>
          )}
          {datas.length > 0 && ended && (
            <div className="left-bottom-tip">
              <i className="icon-coms-organization-down" />
              <span>{getLabel(382630, '没有其他协作了')}</span>
            </div>
          )}
        </WeaNewScrollPagination>
      </div>
    );
  }

  changeTabKey = (tabKey) => {
    const { setParams, reloadLeftList, config } = this.props.coworkMainStore;
    let params = {};
    switch (tabKey) {
      case 'all':
        params = { type: 'all', labelid: 'allTab', layout: 1 };
        break;
      case 'unread':
        params = { type: 'unread', labelid: '1', layout: 1 };
        break;
      case 'important':
        params = { type: 'important', labelid: '2', layout: 1 };
        break;
      case 'hidden':
        params = { type: 'hidden', labelid: '3', layout: 1 };
        break;
      default: {
        const label = config.labelList;
        let sign = {};
        label.map((lab) => {
          if (tabKey == lab.id) {
            return (sign = lab);
          }
        });
        params = { type: sign.labelType, labelid: sign.id, layout: 1 };
        break;
      }
    }
    this.state.tabKey = tabKey;
    setParams(params);
    reloadLeftList();
  };

  changeListKey = (item) => {
    let { setParams, reloadLeftList, config } = this.props.coworkMainStore;
    const label = config.labelList;
    let params = {},
      sign = {};
    label.map((lab) => {
      if (item.key == lab.id) {
        return (sign = lab);
      }
    });
    params = { type: sign.labelType, labelid: sign.id, layout: 1 };
    this.state.tabKey = tabKey;
    setParams(params);
    reloadLeftList();
  };

  changeThemeKey = (key) => {
    const { coworkMainStore } = this.props;
    coworkMainStore.leftList.form.updateFields({
      jointype: {
        value: key,
      },
    });
    coworkMainStore.setStoreState({ formJoinType: key });
    coworkMainStore.reloadLeftList();
    coworkMainStore.changeJoinType({ joinType: key });
  };

  changeSortKey = (key) => {
    const { coworkMainStore } = this.props;
    coworkMainStore.setParams({ orderType: key, layout: 1 });
    coworkMainStore.reloadLeftList();
  };

  search = () => {
    const { coworkMainStore } = this.props;
    const {
      setParams,
      reloadLeftList,
      formJoinType,
      leftList,
      setStoreState,
    } = coworkMainStore;
    const { jointype } = leftList.form.getFormParams();
    if (formJoinType !== jointype) {
      setStoreState({ formJoinType: jointype });
    }
    setParams({ layout: 1 });
    reloadLeftList();
  };

  mark = (item) => {
    const { coworkMainStore } = this.props;
    if (item.key == 'tag') {
      coworkMainStore.getCoworkLabelList();
      coworkMainStore.setTagVisible(true);
      return;
    }
    let checkIds = coworkMainStore.leftList.checkIds;
    if (!checkIds || checkIds.length == 0) {
      message.info(getLabel(4902, '请选择要标记的协作', 'note'));
      return;
    }
    let ids = checkIds.join();
    coworkMainStore.markItemAsType({ coworkids: ids, type: item.key });
    coworkMainStore.setLeftListParams({ checkIds: [], checkAll: false });
  };
}

export default CoworkList;
